/*
 * Copyright (C) 2009 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.dao.db.exec;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang.StringUtils;

import cc.aileron.accessor.PojoAccessorValueNotFoundException;
import cc.aileron.accessor.PojoPropertiesNotFoundException;
import cc.aileron.commons.instance.InstanceManager;
import cc.aileron.dao.db.G2DaoNoCondition;
import cc.aileron.dao.db.G2DaoSerial;
import cc.aileron.dao.db.G2DaoSqlMap;
import cc.aileron.dao.db.G2DbName;
import cc.aileron.dao.db.sql.SqlNotFoundRuntimeException;

/**
 * @author Aileron
 * @param <T>
 * 
 */
public class G2DaoExecuteInvokerImpl<T> implements G2DaoExecuteInvoker<T>
{
    @Override
    public Number execute(final G2DbName dbName, final Connection connection,
            final Class<?> type, final Object condition,
            final Category category, final T bean)
            throws SQLException, PojoAccessorValueNotFoundException,
            PojoPropertiesNotFoundException
    {
        final PreparedStatement statement;
        switch (category)
        {
        case INITIALIZE:
            statementFactory.create(dbName, "initialize", connection, condition);
            return null;

        case INSERT:
            statement = statementFactory.create(dbName,
                    "insert",
                    connection,
                    bean);
            break;

        case UPDATE:
            final String updateSqlName;
            if (condition == G2DaoNoCondition.NO_CONDITION)
            {
                updateSqlName = category.name().toLowerCase();
            }
            else
            {
                updateSqlName = category.name().toLowerCase()
                        + getSqlName(condition, type);
            }
            statement = statementFactory.create(dbName,
                    updateSqlName,
                    connection,
                    condition);
            break;

        case DELETE:
            final String name = category.name().toLowerCase()
                    + getSqlName(condition, type);
            statement = statementFactory.create(dbName,
                    name,
                    connection,
                    new G2DaoObject(condition, bean));
            break;

        default:
            throw new Error("case式が不正です");
        }

        try
        {
            if (!statement.execute())
            {
                return 0;
            }
            if (Category.INSERT == category)
            {
                return serial.getSerialNumber(statement);
            }
            return statement.getUpdateCount();
        }
        finally
        {
            statement.close();
        }
    }

    @Override
    public void execute(final G2DbName dbName, final Connection connection,
            final Class<?> type, final Object condition,
            final G2DaoInvoker invoker)
            throws SQLException, PojoPropertiesNotFoundException,
            PojoAccessorValueNotFoundException
    {
        final String name = invoker.method().sqlFileNamePrefix()
                + getSqlName(condition, type);

        final PreparedStatement preparedStatement = statementFactory.create(dbName,
                name,
                connection,
                condition);
        if (!preparedStatement.execute())
        {
            preparedStatement.close();
            return;
        }
        final ResultSet resultSet = preparedStatement.getResultSet();
        try
        {
            invoker.execute(resultSet);
        }
        catch (final SQLException e)
        {
            throw e;
        }
        catch (final PojoAccessorValueNotFoundException e)
        {
            throw e;
        }
        catch (final PojoPropertiesNotFoundException e)
        {
            throw e;
        }
        finally
        {
            resultSet.close();
            preparedStatement.close();
        }
    }

    /**
     * @param o
     * @return sql-name の取得
     */
    private String getName(final Object o)
    {
        if (o instanceof Enum<?>)
        {
            return ((Enum<?>) o).name();
        }
        if (o instanceof Class<?>)
        {
            final Class<?> instance = (Class<?>) o;
            return instance.getSimpleName();
        }
        final Class<?> oc = o.getClass();
        final String name = oc.getSimpleName();
        if (!StringUtils.isEmpty(name))
        {
            return name;
        }
        final Class<?>[] interfaces = oc.getInterfaces();
        if (interfaces.length == 0)
        {
            throw new NotFoundImplementsInterfaceError(oc);
        }
        return oc.getInterfaces()[0].getSimpleName();
    }

    /**
     * @param condition
     * @param condition
     * @return sqlName
     */
    private String getSqlName(final Object condition, final Class<?> o)
    {
        final String type = o == null ? getName(condition) : o.getSimpleName();
        if (StringUtils.isEmpty(type))
        {
            throw new SqlNotFoundRuntimeException("type name is empty");
        }
        if (condition == G2DaoNoCondition.NO_CONDITION)
        {
            return "All";
        }
        return type;
    }

    /**
     * @param targetClass
     * @param serial
     * @param sqlMap
     * @param provider
     */
    public G2DaoExecuteInvokerImpl(final Class<T> targetClass,
            final G2DaoSerial serial, final G2DaoSqlMap sqlMap,
            final InstanceManager provider)
    {
        this.serial = serial;
        this.statementFactory = provider.get(PreparedStatementProvider.class)
                .get(targetClass, sqlMap, provider);
    }

    /**
     * serial
     */
    private final G2DaoSerial serial;

    /**
     * statementFactory
     */
    private final PreparedStatementFactory<T> statementFactory;
}
